package com.ywfStudy.ywfliving.commodity.service.impl;

import com.ywfStudy.ywfliving.commodity.entity.*;
import com.ywfStudy.ywfliving.commodity.service.*;
import com.ywfStudy.ywfliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywfStudy.common.utils.PageUtils;
import com.ywfStudy.common.utils.Query;

import com.ywfStudy.ywfliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    /**
     *保存SpuSaveVo对象数据保存到对应表中【根据业务，分别保存到不同表中】
     * @Transactional: 方法涉及到对多表的添加，需要加上事务管理的注解
     * */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        //保存spu基本信息到 commodity_spu_info 表中
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //将spuSaveVO 对拷到 spuInfoEntity 对象【属性名需要有对应关系】
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        //将spuInfoEntity 保存到数据库 commodity_spu_info 表中
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存spu介绍图片的信息，对应的表 commodity_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //这里我们设置给spuInfoDescEntity对的Id就是上面添加的spuInfoEntity自动增长的id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

        //判断有几个图片路径
        if (decript.size() == 0){
            spuInfoDescEntity.setDecript("default.jpg");
        }else { // 如果有介绍图片，就进行遍历          1.jpg,2.jpg
            spuInfoDescEntity.setDecript(String.join(",", decript));
        }
        //保存spuInfoDescEntity
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //保存spu对应的图片信息
        //得到images
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 保存spu对应的基本属性组
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        //遍历baseAttrs，封装到ProductAttrValueEntity根据相应业务要求完成
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            //创建ProductAttrValueEntity
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrSort(0); // 默认值
            //这里我们发现前端没有通过json把基本属性name携带过来，这里需要我们二次处理
            //通过attrId获取到属性信息
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            return productAttrValueEntity;
        }).collect(Collectors.toList());
        //将productAttrValueEntities批量保存到对应的表中
        productAttrValueService.saveBatch(productAttrValueEntities);

        //保存sku的基本信息
        //前端发送的SKU信息是多个的,对应的是一个集合
        List<Skus> skus = spuSaveVO.getSkus();
        //将skus遍历处理处理保存到SkuInfoEntity
        if(skus != null && skus.size() != 0) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                // 处理默认图片
                String defaultImg = "default.jpg";

                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L); // 销量默认
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setPrice(item.getPrice());
                skuInfoEntity.setSkuName(item.getSkuName());
                skuInfoEntity.setSkuTitle(item.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());
                //保存sku基本信息到表中
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //item取出图片集合
                //收集集合时要过来imgUrl为空的情况
                List<SkuImagesEntity> collect = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(img->{
                    // 过滤img对象imgurl为空的数据
                    return StringUtils.isNotBlank(img.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);

                //保存sku的销售属性 对应的表-对应的表是commodity_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();

                //遍历attrs集合
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(saleAttrs -> { //saleAttr就是一个销售属性
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(saleAttrs.getAttrId());
                    skuSaleAttrValueEntity.setAttrName(saleAttrs.getAttrName());
                    skuSaleAttrValueEntity.setAttrSort(0);
                    skuSaleAttrValueEntity.setAttrValue(saleAttrs.getAttrValue());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //批量保存销售属性
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    //通过携带的检索条件,进行分页查询
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //检索条件-key
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            wrapper.and(w->{
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        //检索条件-状态
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)){
            wrapper.eq("publish_status", status);
        }
        //检索条件--品牌id
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id", brandId);
        }
        //检索条件-分类id
        String catalogId = (String) params.get("catalogId");
        if (StringUtils.isNotBlank(catalogId) && !"0".equalsIgnoreCase(catalogId)){
            wrapper.eq("catalog_id", catalogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 1);
    }

    @Override
    public void down(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 2);
    }

}